package com.jdzy.student.service.impl;

import com.jdzy.student.properties.MinioProperties;
import com.jdzy.student.service.FileService;
import com.jdzy.student.service.StudentBaseInformationService;
import com.jdzy.student.service.StudentService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioProperties properties;

    @Autowired
    private MinioClient client;
    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentBaseInformationService studentBaseInformationService;


//    @Override
//    public String upload(MultipartFile file, String stuId) {
//        try {
//            boolean bucketExists = client.bucketExists(BucketExistsArgs.builder().bucket(properties.getBucketName()).build());
//            if (!bucketExists) {
//                client.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
//                client.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(properties.getBucketName()).config(createBucketPolicyConfig(properties.getBucketName())).build());
//            }
//
//            String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
//            client.putObject(PutObjectArgs.builder().
//                    bucket(properties.getBucketName()).
//                    object(filename).
//                    stream(file.getInputStream(), file.getSize(), -1).
//                    contentType(file.getContentType()).build());
//
//            return String.join("/", properties.getEndpoint(), properties.getBucketName(), filename);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    @Override
    public String upload(MultipartFile file, String stuId) {
        try {
            boolean bucketExists = client.bucketExists(BucketExistsArgs.builder().bucket(properties.getBucketName()).build());
            if (!bucketExists) {
                client.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
                client.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(properties.getBucketName()).config(createBucketPolicyConfig(properties.getBucketName())).build());
            }

            String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
            client.putObject(PutObjectArgs.builder()
                    .bucket(properties.getBucketName())
                    .object(filename)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType()).build());

            String url = String.join("/", properties.getEndpoint(), properties.getBucketName(), filename);

            // 更新学生表和学生基础信息表中的 avatar 字段
            studentService.updateAvatar(stuId, url);
            studentBaseInformationService.updateAvatar(stuId, url);

            return url;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String createBucketPolicyConfig(String bucketName) {

//        return """
//            {
//              "Statement" : [ {
//                "Action" : "s3:GetObject",
//                "Effect" : "Allow",
//                "Principal" : "*",
//                "Resource" : "arn:aws:s3:::%s/*"
//              } ],
//              "Version" : "2012-10-17"
//            }
//            """.formatted(bucketName);
        String policy = "{\n" +
                "  \"Statement\" : [ {\n" +
                "    \"Action\" : \"s3:GetObject\",\n" +
                "    \"Effect\" : \"Allow\",\n" +
                "    \"Principal\" : \"*\",\n" +
                "    \"Resource\" : \"arn:aws:s3:::%s/*\"\n" +
                "  } ]\n" +
                "  \"Version\" : \"2012-10-17\"\n" +
                "}";
        String policyWithBucketName = String.format(policy, bucketName);
        return policyWithBucketName;
    }


}
